const Form = require('../models/form')
const FormData = require('../models/formData')
const formDesign = require('./form_design')

const getForm = async (id) => {
	return await Form.findById(id);
}

const getFormData = async (id) => {
	return await FormData.findById(id);
}

const getFormList = async () => {
	return await Form.find({});
}

const getFormDataList = async (id) => {
	return await FormData.find({form_id: id});
}

const saveForm = async (form) => {
	if (!form.id) {
		const newForm = new Form({...form, create_time: new Date()}).save();
		return newForm;
	} else {
		let updated = await Form.findByIdAndUpdate(form.id, form).exec()
		return updated;
	}
}

const saveDesign = async (id, content) => {
	let parse_form = formDesign.parse_form(content, 0);
	parse_form.content = content;
	if (id) {
		let updated = await Form.findByIdAndUpdate(id, 
			{
				content: parse_form.content, 
				content_parse: parse_form.parse, 
				content_data: parse_form.data, 
				fields: parse_form.fields,
				add_fields: parse_form.add_fields,
				update_time: new Date()
			}).exec()
		return updated;
	} else {
		let newForm = await saveNewDesign(parse_form);
		return newForm;
	}
}

const saveNewDesign = async (parse_form) => {
	let newForm = await new Form( 
		{
			content: parse_form.content, 
			content_parse: parse_form.parse, 
			content_data: parse_form.data, 
			fields: parse_form.fields,
			add_fields: parse_form.add_fields,
			form_name: 'new form',
			form_desc: 'new form',
			create_time: new Date()
		}).save()
	return newForm;
}

const getFormPreview = async (id) => {
	let form = await Form.findById(id);
	let parse_form = formDesign.parse_form(form.content, 0);
	var template = formDesign.unparse_form(parse_form, {}, {action:'preview'})
	
	return {form_name: form.form_name, design_content: template};
}

const getFormEdit = (form, data, action) => {
	let parse_form = formDesign.parse_form(form.content, 0);
	var template = formDesign.unparse_form(parse_form, data, {action})

	return {design_content: template};
}

const saveFormData = async (form, data) => {
	let form_id = data.form_id;
	let id = data.id;
	let name = data.name;
	delete data.form_id;
	delete data.id;
	delete data.name;
	delete data.submit_to_save;
	formDesign.convertData(form, data);
	data = formDesign.unparse_data(form, data);
	let formData = null;
	if (!id) {
		formData = await new FormData({form_id, name, data, create_time: new Date()}).save()
	} else {
		formData = await FormData.findByIdAndUpdate(id, {name, data, update_time: new Date()})
	}
	return formData;
}

module.exports = { getForm, getFormData, getFormList, getFormDataList, saveForm, saveDesign, saveNewDesign, saveFormData,
	getFormPreview, getFormEdit }
